package com.pospi.xstore.ui.vip_ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.kyleduo.switchbutton.SwitchButton;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.caigou.CgDetailActivity;
import com.pospi.xstore.ui.caigou.CgshListActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VIPRegisterActivity extends BaseActivity implements OnCheckedChangeListener {

    @Bind(R.id.et_vip_name)
    EditText etVipName;
    @Bind(R.id.et_vip_phone)
    EditText etVipPhone;
    @Bind(R.id.tv_vip_birth)
    TextView tvVipBirth;
    @Bind(R.id.tv_vip_sex)
    TextView tvVipSex;
    @Bind(R.id.tv_vip_email)
    EditText tvVipEmail;
    @Bind(R.id.tv_vip_address)
    EditText tvVipAddress;
    @Bind(R.id.sb_msg)
    SwitchButton sbMsg;
    @Bind(R.id.tv_vip_sfz)
    EditText tv_vip_sfz;
    @Bind(R.id.tv_vip_pass)
    EditText tv_vip_pass;
    @Bind(R.id.tv_vip_cat)
    TextView tv_vip_cat;
//    @Bind(R.id.sb_leaflet)
//    SwitchButton sbLeaflet;
    @Bind(R.id.btn_cancle)
    TextView btnCancle;
    @Bind(R.id.btn_sure)
    TextView btnSure;
    private final String TAG = "VIPRegisterActivity.tag";
    private List<VipType> types = new ArrayList<>();
    private List<String> mStrings = new ArrayList<>();
    private String typeid;
    private String ischoose = "0";
    private VipBeen vipBeen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_vipregist);
        setTitle("会员注册");
        ButterKnife.bind(this);
        vipBeen = (VipBeen) getIntent().getSerializableExtra("data");
        if (vipBeen != null) {
            setTitle("会员修改");
            etVipName.setText(vipBeen.getName());
            etVipPhone.setText(vipBeen.getTel());
            btnSure.setText("修改");
        }

        getviptype();
        tvVipBirth.setText(GetData.getYYMMDDTime());

        sbMsg.setOnCheckedChangeListener(this);
    }

    @OnClick({R.id.tv_vip_birth, R.id.tv_vip_sex, R.id.btn_cancle, R.id.btn_sure ,R.id.tv_vip_cat})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_vip_cat:
                mStrings.clear();
                for (VipType type : types) {
                    mStrings.add(type.getName());
                }
                creatDialog(mStrings);

                break;
            case R.id.tv_vip_birth:
                long mixYears = 80L * 365 * 1000 * 60 * 60 * 24L;
                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setThemeColor(R.color.title)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setMinMillseconds(System.currentTimeMillis() - mixYears)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                tvVipBirth.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
            case R.id.tv_vip_sex:
                creatSexDialog();
                break;
            case R.id.btn_cancle:
                finish();
                break;
            case R.id.btn_sure:
                register();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.sb_msg://是否启用密码
                if (isChecked) {
                    ischoose = "1";
                } else {
                    ischoose = "0";
                }
                break;

        }
    }

    private String[] sexs = new String[]{"男","女"};
    private void creatSexDialog() {

        new CircleDialog.Builder(this)
                .setItems(sexs, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        tvVipSex.setText(sexs[i]);
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("注册成功")
                            .setPositive("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    VIPRegisterActivity.this.finish();
                                }
                            })
                            .show(getSupportFragmentManager());
                    break;
                case 2:
                    close();
                    Toast.makeText(VIPRegisterActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    close();
                    Toast.makeText(VIPRegisterActivity.this, "手机号已经被注册", Toast.LENGTH_SHORT).show();
                    break;
                case 4:

                    break;
            }

        }
    };
    private void creatDialog(final List<String> strings) {

        new CircleDialog.Builder(this)
                .setItems(strings, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        tv_vip_cat.setText(strings.get(i));
                        typeid = types.get(i).getId();
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }

    private void register(){
        showDialog();
        RequestParams params = new RequestParams();
        params.put("model", "vip.Vvip");
        params.put("fun", "save");//find   filter
        params.put("table", "vip_info");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));


        JSONObject object = new JSONObject();
        try {
            if (vipBeen != null) {
                object.put("id", vipBeen.getId());
            } else {
                object.put("id", "0");
            }

            object.put("num", etVipPhone.getText().toString().trim());
            object.put("name", etVipName.getText().toString().trim());
            object.put("channel", "线下门店");
            object.put("sex", tvVipSex.getText().toString());
            object.put("typeid", typeid);

            object.put("status", "1");
            object.put("marketid", SPHelper.getInstance().getString(Constant.STORE_ID));
            object.put("birthday", tvVipBirth.getText().toString());
            object.put("pwd", tv_vip_pass.getText().toString().trim());
            object.put("tel", etVipPhone.getText().toString().trim());

            object.put("sfzh", tv_vip_sfz.getText().toString().trim());
            object.put("addr", tvVipAddress.getText().toString().trim());
            object.put("email", tvVipEmail.getText().toString().trim());
            object.put("qq", "");
            object.put("wx", "");

            object.put("dw", "");
            object.put("zy", "");
            object.put("sr", "");
            object.put("personid", "");
            object.put("xfcs", "");


            object.put("xfje", "");
            object.put("jfye", "");
            object.put("mzye", "");
            object.put("lastxfrq", "");
            object.put("lastmemo", "");
            object.put("memo", "");
            object.put("ispwd", ischoose);//0不启用 ，1启用

        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.put("pds", object.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i(TAG, new String(bytes));
                try {
                    final JSONObject object = new JSONObject(new String(bytes));


                    if (!object.getString("errCode").equals("100")) {
                        Message message = Message.obtain();
                        message.what = 2;
                        message.obj = object.getString("errMsg");
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });

    }
    private void getviptype(){
        RequestParams params = new RequestParams();
        params.put("model", "vip.Vvip");
        params.put("fun", "getviptype");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));

        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i(TAG, new String(bytes));


                try {
                    final JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("errCode").equals("105")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Toast.makeText(VIPRegisterActivity.this, object.getString("errMsg"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    types = new Gson().fromJson(object.getJSONArray("result").toString(), new TypeToken<List<VipType>>() {
                    }.getType());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }

}
